package com.xiaoyi.springboot.listener;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class MqListener {
    @RabbitListener(queues = {"mysteel.oilchem.research.test.queue"})
    @RabbitHandler
    public void handle(Message message) {
        List<Object> itemTaskList = getItemTaskList(message);
        log.info("返回数据：{}", JSON.toJSONString(itemTaskList));
    }
    /**
     * 从mq消息中拿到计算因子任务数据列表
     *
     * @param message
     * @return
     */
    private List<Object> getItemTaskList(Message message) {
        List<Object> itemTaskList = new ArrayList<>();
        if (message == null || message.getBody() == null || message.getBody().length == 0) {
            log.warn("message 为空,{}", message);
            return itemTaskList;
        }
        String body = null;
        try {
            body = new String(message.getBody(), StandardCharsets.UTF_8);
            log.info("计算消息message={}", body);
            MQMessage mqMessage = JSON.parseObject(body, MQMessage.class);
            if (mqMessage == null || CollectionUtils.isEmpty(mqMessage.getData())) {
                return itemTaskList;
            }
            return mqMessage.getData();

        } catch (Exception e) {
            log.error("计算消息消费异常,message deliveryTag={}", body, e);
        }
        return itemTaskList;
    }
}
